#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import logging
import re
import time
import asyncio
import base64
from datetime import datetime

from sqlalchemy import func
import aiohttp

from . import db


def filter_fields_dict(item, fields=[]):
    return {key: val for key, val in item.items() if key in fields}


def filter_fields_dict_list(items, fields=[]):
    return [filter_fields_dict(item, fields) for item in items]


async def load_page(tableName, index, *, pagesize=12, filter={'name': None, 'status': None}, order_by={'id': True, 'created_date': True}):
    table_ = getattr(db, tableName)
    session = db.create_session()
    filter_ = []
    if filter.get('path', None):
        filter_.append(table_.path == filter.get('path', '/'))
    order_by_ = []
    for key, rev in order_by.items():
        if rev:
            order_by_.append(table_.__dict__[key])
        else:
            order_by_.append(table_.__dict__[key].desc())
    total = session.query(func.count(table_.id)).filter(*filter_).scalar()
    items = [item.single_to_dict() for item in session.query(table_).filter(
        *filter_).order_by(*order_by_).offset((index - 1) * pagesize).limit(pagesize)]
    pages = ((total - 1) // pagesize) + 1 if pagesize > 0 else 0
    return {'page': {'total': total, 'pages': pages, 'index': index, 'size': pagesize}, 'items': items}


async def load_items(tableName, filter={'name': None, 'status': None}, in_={}, order_by={'id': True, 'created_date': True}):
    table_ = getattr(db, tableName)
    session = db.create_session()
    filter_ = []
    if filter.get('path', None):
        filter_.append(table_.path == filter.get('path', '/'))
    for key, val in filter.items():
        if val is None:
            continue
        filter_.append(getattr(table_, key) == val)
    if len(in_.keys()) > 0:
        for key, val in in_.items():
            if not isinstance(val, list):
                continue
            filter_.append(getattr(table_, key).in_(val))
    order_by_ = []
    for key, rev in order_by.items():
        if rev:
            order_by_.append(table_.__dict__[key])
        else:
            order_by_.append(table_.__dict__[key].desc())
    items = [item.single_to_dict() for item in session.query(
        table_).filter(*filter_).order_by(*order_by_)]
    return {'items': items}


def save(tableName='', items=[]):
    if len(tableName) is None:
        return
    table_ = getattr(db, tableName)
    if table_ is None:
        return
    if len(items) <= 0:
        return
    session = db.create_session()
    item_dict = {item['id']: item for item in items if item.__contains__('id')}
    print('-' * 25)
    print(items)
    print('-' * 25)
    items_ = [item for item in session.query(
        table_).filter(table_.id.in_(item_dict.keys()))]

    for item in items_:
        for key, value in item_dict[item.id].items():
            if key.startswith('updated_') or key.startswith('created_'):
                continue
            setattr(item, key, value)
        item.updated_at = datetime.now()
        item.updated_date = item.updated_at.strftime('%Y%m%d')
        item.updated_stamp = item.updated_at.timestamp()

    for obj in items:
        if obj.__contains__('id'):
            continue
        item = table_()
        print('-' * 25)
        print(obj)
        print('-' * 25)
        for key, value in obj.items():
            if key.startswith('updated_') or key.startswith('created_'):
                continue
            setattr(item, key, value)
        session.add(item)
    session.commit()


def delete(tableName='', ids=[]):
    if len(tableName) is None:
        return
    table_ = getattr(db, tableName)
    if table_ is None:
        return
    if len(ids) <= 0:
        return
    session = db.create_session()
    items = [item for item in session.query(table_).filter(table_.id.in_(ids))]
    for item in items:
        if item is not None and hasattr(item, 'content_type') and item.content_type == 'd':
            delete(tableName, [item.id for item in session.query(table_).filter_by(
                table_.path == '%s/%s' % (item.path, item.name))], session)
        session.delete(item)
    session.commit()


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("-d", "--download", help="download <url>",
                        action="store_true", dest="is_download", default=False)
    parser.add_argument("--text", help="--text <text>")
    parser.add_argument("--filename", help="--filename <filename>")
    parser.add_argument("--url", help="--url <vemss|ss>")
    parser.add_argument("--proxy", help="--proxy <proxy url>")
    args = parser.parse_args()
    parser.print_help()
